<template>
  <div>
    <el-form label-position="top" ref="form" :model="form" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-button style="float:right;margin-bottom: 8px" size="mini" @click="addProduct">添加产品</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-table ref="productDialogTable" :data="form.productList" style="width: 100%" max-height="225px">
            <el-table-column show-overflow-tooltip fixed align="center" prop="productName" label="产品名称"
                             min-width="155"
            />
            <el-table-column show-overflow-tooltip align="center" prop="categoryName" label="产品类别"
                             min-width="95"
            />
            <el-table-column show-overflow-tooltip align="center" prop="unit" label="单位" min-width="95">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_crm_product_unit" :value="scope.row.unit"/>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="price" label="标准价格" min-width="95"/>
            <el-table-column show-overflow-tooltip align="center" prop="salesPrice" label="售价" min-width="155">
              <template slot-scope="scope">
                <el-input-number :key="key" @change="valueChange(scope.row,'salesPrice', $event)" style="width: 85%"
                                 size="mini"
                                 v-model="scope.row.salesPrice" :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="num" label="数量" min-width="155">
              <template slot-scope="scope">
                <el-input-number :key="key" @change="valueChange(scope.row,'num', $event)" style="width: 85%"
                                 size="mini"
                                 v-model="scope.row.num" :min="1"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="discount" label="折扣（%）" min-width="155">
              <template slot-scope="scope">
                <el-input-number :key="key" @change="valueChange(scope.row,'discount', $event)" style="width: 85%"
                                 size="mini"
                                 v-model="scope.row.discount" :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="subtotal" label="合计" min-width="95"/>
            <el-table-column show-overflow-tooltip align="center" label="操作" min-width="135">
              <template slot-scope="scope">
                <el-button type="text" @click.native.prevent="deleteRow(scope.$index, form.productList)">移出
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="remark" style="margin-top: 12px">
            整单折扣（%）：
            <el-input-number style="width: 30%;margin-right: 8px" v-model="form.discountRate"
                             @change="discountRateChange" controls-position="right" :min="0"
            ></el-input-number>
            选中 {{ form.productList.length }} 种，总金额 {{ form.money }} 元
          </el-form-item>
        </el-col>
      </el-row>
      <product-select-popover ref="productSelectPopover" @callback="productSelectCallback"/>
    </el-form>
  </div>
</template>

<script>
import ProductSelectPopover from '@/components/Crm/Product/ProductSelectPopover'

export default {
  name: 'DialogAddProduct',
  dicts: ['sys_crm_product_category', 'sys_crm_product_unit'],
  components: {
    ProductSelectPopover
  },
  props: {},
  data() {
    return {
      form: {
        money: 0,// 商机金额
        discountRate: 0,// 整单折扣
        productList: []// 产品集合
      },
      key: 0
    }
  },
  // 在实例创建完成后被立即调用
  created() {

  },
  // 实例被挂在后调用
  mounted() {

  },
  // 方法
  methods: {
    // 添加产品
    addProduct() {
      this.$nextTick(() => {
        this.$refs.productSelectPopover.open()
      })
    },
    // 整单折扣发生变化调用
    discountRateChange() {
      this.calculateProductPrice()
      // 计算整单折扣后的最终价格
      this.updateTotalPrice()
    },
    // 初始化数据
    initProductData(initData) {
      this.form.productList = initData.productList
      if (initData.discountRate == null) {
        this.form.discountRate = 0
      } else {
        this.form.discountRate = initData.discountRate
      }
      this.calculateProductPrice()
      // 计算整单折扣后的最终价格
      this.updateTotalPrice()
    },
    // 计数器发生变化时触发
    valueChange(row, dataIndex, event) {
      this.key = this.key + 1
      const dataSource = [...this.form.productList]
      const target = dataSource.find(item => item.id === row.id)
      if (target) {
        target[dataIndex] = parseInt(event)
        this.form.productList = dataSource
      }
      // 计算总价
      this.calculateSalePrice()
      this.calculateProductPrice()
      // 计算整单折扣后的最终价格
      this.updateTotalPrice()
    },
    // 计算产品单个总价
    calculateSalePrice() {
      const newProductData = this.form.productList.map(it => {
        it.subtotal = it.salesPrice * it.num * (100 - it.discount) / 100
        return it
      })
      this.form.productList = newProductData
    },
    // 计算产品总体价格
    calculateProductPrice() {
      var totalPrice = 0
      for (var i = 0; i < this.form.productList.length; i++) {
        totalPrice += this.form.productList[i].subtotal
      }
      this.form.money = totalPrice
    },
    // 计算总体折扣后的价格
    updateTotalPrice() {
      this.form.money = this.form.money * (100 - this.form.discountRate) / 100
      // 通知父组件，价格发生变化
      this.$emit('callback', this.form)
    },
    // 移出
    deleteRow(index, rows) {
      this.form.productList.splice(index, 1)
      // 重新计算总价
      this.calculateProductPrice()
      // 计算整单折扣后的最终价格
      this.updateTotalPrice()
    },
    // 选中产品数据回调
    productSelectCallback(productData) {
      this.form.productList = productData
      for (let i = 0; i < this.form.productList.length; i++) {
        this.form.productList[i].salesPrice = this.form.productList[i].price
        this.form.productList[i].num = 1
        this.form.productList[i].discount = 0
      }
      // 调用计算总价方法
      this.calculateSalePrice()
      this.calculateProductPrice()
      // 计算整单折扣后的最终价格
      this.updateTotalPrice()
    }
  }
}
</script>

<style scoped>

</style>
